<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" class="preview" alt="" v-if="avatar" />
      <img src="../../assets/images/avatar.jpg" class="preview" alt="" v-else />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" accept="image/*" @change="onFileChange" :style="{display:'none'}" ref="inpRef">
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" @click="onloadImg" :disabled="avatar==null">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: null
    }
  },
  methods: {
    // onFileChange (e) {
    //   const files = e.target.files
    //   if (files.length === 0) {
    //     this.avatar = ''
    //   } else {
    //     console.log(files[0])
    //   }
    // },
    onFileChange () {
      const files = this.$refs.inpRef.files
      if (files && files.length > 0) {
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = e => {
          this.avatar = e.target.result
        }
      } else {
        this.avatar = null
      }
    },
    chooseImg () {
      this.$refs.inpRef.click()
    },
    async onloadImg () {
      const res = await this.$http.patch('/my/update/avatar', { avatar: this.avatar })
      if (res.data.code === 1) return this.$message.error(res.data.message)
      this.$message.success(res.data.message)
      this.$store.dispatch('initUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.preview {
  width: 350px;
  height: 350px;
}
</style>
